package io.web.gateway;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.time.Duration;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * GatewayApplication.
 * Test api-interface {@link io.web.api.controller.PathController}
 * {@link GlobalFilter} 针对所有路由
 * {@link GatewayFilter} 针对指定路由
 *
 * @date 2023-05-29
 */
@SpringBootApplication
@EnableFeignClients
public class GatewayApplication {

    public static void main(String[] args) {
        ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
        System.out.println(now + " " + ZoneId.systemDefault());
        SpringApplication.run(GatewayApplication.class, args);
    }

    //    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("routebd", r -> r.path("/bd")
                        .uri("http://localhost:8000"))
                .route("host_route", r -> r.host("*.myhost.org")
                        .uri("http://httpbin.org"))
                .build();
    }

//    @Bean
    public Customizer<ReactiveResilience4JCircuitBreakerFactory> myCircuitBreaker() {
        return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
                .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)).build()).build());
    }
}
